package com.wangt.biz.util;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class DataUtils {
    public DataUtils() {
    }

    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToByteArrs(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }

        return bytes;
    }

    /**
     * 数组转换成十六进制字符串
     *
     * @param bArray
     * * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
            // 在这里故意追加一个逗号便于最后的区分
            sb.append(" ");
        }
        return sb.toString();
    }

    /**
     * 16进制字符串转换成为ASSCII码字符串
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     *  从byte数组中offset下标开始取len个字节数据，按大端（高字节在前，低字节在后）拼接成对应的无符号int数据
     *  处理双字节或四字节数据
     * @param buff
     * @param offset
     * @param len
     * @return
     */

    public static int ConvertByteToInt(byte [] buff,int offset,int len)
    {
        int result=0;
        if(len>4)
        {
            len=4;
        }
        for(int i=0;i<len;i++)
        {
            result <<= 8;
            result|=Byte.toUnsignedInt(buff[offset+i]);
        }
        return result;
    }


    /**
     * 数据解析（每次取4字节）
     * @param parmTable
     * @param buff
     * @param elemSize
     * @param count
     */

    public static  void GetParam(int [] parmTable,byte [] buff,int elemSize,int count)
    {
        if(count*elemSize > buff.length)
        {
            return;
        }
        char [] charArray=getChars(buff);
        String str = new String(charArray);
        for (int i=0;i<count;i++)
        {
            parmTable[i]=Integer.valueOf(str.substring(i*elemSize,elemSize),10);
        }
    }

    /**
     * char[] 数组转为byte[] 数组
     * @param chars
     * @return
     */
    public static byte[] getBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        return bb.array();
    }

    /**
     * byte[] 数组转为数组 char[]
     * @param bytes
     * @return
     */
    public static char[] getChars(byte[] bytes) {
        Charset cs = Charset.forName("UTF-8");
        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes);
        bb.flip();
        CharBuffer cb = cs.decode(bb);
        return cb.array();
    }

    /**
     * 16进制字符串转换为10进制数字
     *
     * @param hexs
     * @return
     */
    public static int decodeHEX(String hexs) {
        BigInteger bigint = new BigInteger(hexs, 16);
        int numb = bigint.intValue();
        return numb;
    }

    /**
     * 根据协议转换
     *
     * @param str
     */
    public static int dataToBaseConversion(String str) {
        //先转10进制
        int temp = decodeHEX(str);
        int temp1, temp2;
        //判断是否为负数
        if (temp > 32767) {
            temp1 = temp - 65536;
            return temp1;
        } else {
            temp2 = temp;
            return temp2;
        }
    }

    /**
     * 字符串拼接日期时间（datetime）
     *
     * @param str1
     */
    public static String stringToStringDateTime(String str1) {
        String[] str = new String[6];
//        str1 = "200918140801";
        String str2 = "";
        for (int i = 0; i < 6; i++) {
            str[i] = str1.substring(i * 2, i * 2 + 2);
            if (i == 0) {
                str2 = "20" + str[i] + "-";
                continue;
            }
            if (i == 1) {
                str2 = str2 + str[i] + "-";
            }
            if (i == 2) {
                str2 = str2 + str[i] + " ";
                continue;
            }
            if (i == 3 || i == 4) {
                str2 = str2 + str[i] + ":";
            }
            if (i == 5) {
                str2 = str2 + str[i];
            }
        }
        return str2;
    }

    /**
     * 截取DTU标识串
     * @param buff
     * @return
     */

    public static String getIdentificationDTU(byte [] buff){
        int dd = ConvertByteToInt(buff,4,4);
        int ee = ConvertByteToInt(buff,8,4);
        int ff = ConvertByteToInt(buff,12,3);
        String identificationDTU = Integer.toHexString(dd)+Integer.toHexString(ee)+Integer.toHexString(ff);
        return identificationDTU;
    }


    public static String ten2Hex1(int num) {
//        num = 120000000;

//        String strHex1 = Integer.toHexString(num).toUpperCase();
        String strHex1 = String.format("%02x", num).toUpperCase();//不足两位高位补0
        return strHex1;
    }

    public static String ten2Hex2(int num) {

//        String strHex1 = Integer.toHexString(valueTen).toUpperCase();//高位不用补0
        String strHex2 = String.format("%08x", num).toUpperCase();//高位补0
        return strHex2;
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }


    /**
     * 将字符串转为指定编码的16进制
     *
     * @param str
     * @return
     */
    public static String encode(String str) throws Exception {
        String hexString = "0123456789ABCDEF";
        //根据编码获取字节数组
        byte[] bytes = str.getBytes("GBK");
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        //将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /**
     * 将字符串转16进制
     *
     * @param str
     * @return
     */
    public static String stringToHex(String str){
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder builder = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            builder.append(chars[bit]);
            bit = bs[i] & 0x0f;
            builder.append(chars[bit]);
//            builder.append(' ');
        }
        return builder.toString().trim();
    }

    /**
     * 将4位16进制字符串转为十进制
     * @param strHex
     * @return
     */
    public static int data16To10(String strHex){
        BigInteger lngNum = new BigInteger(strHex,16);
        return lngNum.intValue();
    }

    /**
     * 将十进制整数转为4位16进制字符串返回
     * @param valueTen
     * @return
     */
    public static String data10To16(int valueTen){
        return String.format("%08X",valueTen);
    }
    public static byte [] intToVyteArray(int valueTen){
        byte [] result=new byte[4];
        result[3]= (byte) (valueTen&0xFF);
        result[2]= (byte) ((valueTen>>8)&0xFF);
        result[1]= (byte) ((valueTen>>16)&0xFF);
        result[0]= (byte) ((valueTen>>24)&0xFF);
        return result;
    }

    /**
     * 将 4字节的16进制字符串，转换为32位带符号的十进制浮点型
     * @param str 4字节 16进制字符
     * @return
     */
    public  static  float hexToFloat(String str){
        return  Float.intBitsToFloat(new BigInteger(str, 16).intValue());
    }

}
